const app = getApp();
import { requestApi } from '../../api'
import { extend } from '../../sdk/extend';
import { dateFormat } from '../../utils/dateFormat';
import { formatImage } from '../../utils/formatImage';
import { logUpload } from '../../utils/logUpload';

Page({
    data: {
        winWidth: wx.getSystemInfoSync().windowWidth,
        winHeight: wx.getSystemInfoSync().windowHeight,
        ratio: 560 / 750,
		top: app.data.top,
		height: app.data.height,
		user_type: 0,   // 0: 不符合条件  1: 新用户   2: 老用户
		info: null,       // 新人专区详情
		coupon_list: [],
		activity_list: [],
		entrenceTime: '',
        isShowRule: false,
        isShowFilter: false, // 是否打开筛选
        filterInfo: null, // 筛选条件信息
        categoryList: [],
        params: {
            gender_id: '',
            keywords: '',
            search_goods_filter: 0,     // (新人专区选择二级筛选时可能会有空结果，暂时先不展示二级筛选)
            goods_channel_source: 1,
            is_new_user_buy: 1
        },
        cur: 0,
        oid: 3,
        start: 0,
        count: 50,
        goodsList: [],
        isFixed: false,
        isMoreEnd: false, // 加载更多
        scrollTop: 0, // 筛选成功后，滚动到顶部
        filterTop: 0,
        filterPaddingTop: 0,
        navBgColor: '',
        navClass: '',
        navOpacity: 0
	},
	onShow() {
        this.getNewUserInfo();
        this.getTypeData();
	},
    onLoad(options) {
		this.data.entrenceTime = dateFormat('yyyy-MM-dd hh:mm:ss:S')

		// 埋点上报
        let uploadParam = {
            cur_page_id: 'OFNewcommerViewController',
            cur_page_entrance_time: dateFormat('yyyy-MM-dd hh:mm:ss:S')
        }

        logUpload.handleUpload(uploadParam);
    },
    getNewUserInfo() {
        const { filterTop } = this.data;
        let userinfo = wx.getStorageSync('userinfo') || null;

		app.request({
            url: requestApi.getNewUserInfo,
            data: {
                is_new_ver: true
            }
        }, (d) => {
            if (d.original.ret_code == 200) {
				const list = d.original.data.item_list;
				let info = {}, coupon_list = [], activity_list = [];

				list.forEach(item => {
					if (item.type == 154) {
                        info['is_show_btn'] = !userinfo ? true : item.data.is_can_receive;
						info['tips'] =  info.is_show_btn ? item.data.new_user_desc : item.data.other_desc;
						info['user_type'] = item.data.user_type;
						info['is_received'] = item.data.is_received;
						info['user_type'] = item.data.user_type;
						info['activity_rule'] = item.data.activity_rule;
                        
                        if (item.data.new_cover_image) {
                            info['bg'] = formatImage.cdnImage(item.data.new_cover_image.path, formatImage.THUMBNAIL_M);
                        }
						
						coupon_list = item.data.coupon_info.coupon_list;
					}

					if (item.type == 155) {
						info['title'] = item.data.title;
						info['subtitle'] = item.data.subtitle;
						info['color'] = item.data.color;
						item.data.image_1.full_path = formatImage.cdnImage(item.data.image_1.path, formatImage.THUMBNAIL_M);
						item.data.image_2.full_path = formatImage.cdnImage(item.data.image_2.path, formatImage.THUMBNAIL_M);
						info['img_1'] = item.data.image_1;
						info['img_2'] = item.data.image_2;

						item.data.items.forEach(itm => {
							itm.cover_image.full_path = formatImage.cdnImage(itm.cover_image.path, formatImage.THUMBNAIL_M);
							itm.cover_image.h = ((app.data.windowWidth - 36) * 0.48) / (itm.cover_image.width / itm.cover_image.height);
						});
						activity_list = item.data.items;
					}
				});

				this.setData({
					info,
					coupon_list,
					activity_list
				},() => {
                    if (!filterTop) {
                        const query = wx.createSelectorQuery();
                        setTimeout(() => {
                            query.select('#filter').boundingClientRect();
                            query.exec((res) => {
                                const top = res[0] && res[0].top || 0;
                                console.log(res);
                                this.setData({
                                    filterTop: top * 1
                                })
                            });
                            
                        }, 100);
                    }
                })
            }
        },
        (error) => {
            wx.showModal({
                title: '提示',
                content: error,
                showCancel: false,
            })
        })
	},
	showRule() {
		const { isShowRule } = this.data;

		this.setData({
			isShowRule: !isShowRule
		})
	},
	goBack() {
        const { isShowFilter } = this.data;

        if (isShowFilter) {
            this.setData({
                isShowFilter: false
            })
        } else {
            wx.navigateBack();
        }
	},
	receiveHandler() {
		const { info } = this.data;
		if(app.toLogin()) {
			if (info.is_received == 1) {
                wx.navigateTo({
                    url: '/pages/personal/coupon/coupon',
                })
			} else {
				this.receiveCoupon();
			}
		}
	},
	goPage(e) {
		const { index } = e.currentTarget.dataset;
		const { activity_list, channel, entrenceTime } = this.data;
		const info = activity_list[index];
        let tid = info.page_id;
        let opt_resource_id = info.page_id;
        let opt_time = dateFormat('yyyy-MM-dd hh:mm:ss:S');
        let opt_resource_type = 1;
        let ref_opt_resource_type = 41;
        let opt_protocol = '';
        let url = '';

        switch(Number(info.page_type)) {
            case 1: // 专题
                opt_protocol = '/pages/topic/topicDetail/topicDetail'

                url = opt_protocol + '?tid=' + tid;
                break;
            case 2: // 合集
                opt_resource_type = 2;
                opt_protocol = '/pages/activity/activityDetail/activityDetail';
                
                url = opt_protocol + '?tId=' + tid;
                break;
            case 4: // 商品
                opt_resource_type = 5;
                opt_protocol = '/pages/goods/goodsDetail/goodsDetail';

                url =  opt_protocol + '?gid=' + tid;
            break;
            case 6: // 外链
                break;
            case 12: // 索引page页
                opt_resource_type = 99;
                opt_protocol = '/pages/categoryHall/categoryHall';

                url =  opt_protocol + '?isKing=true&tid=' + tid;
            break;
            case 13: // 秒杀专场
                opt_resource_type = 2;
                opt_protocol = '/pages/webView/webView';

                url = 'channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index;
            break;
            default:
        }

        if (info.resource_type != 6) {
            if (info.resource_type == 13) {
                url = encodeURIComponent(url)
                wx.navigateTo({
                    url: `/pages/webView/webView?urlParams=${url}&type=flashsale&tid=${tid}`,
                })
            } else {
                wx.navigateTo({
                    url: url + '&channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index
                });
            }
        }
	},
	// 新手优惠，一键领取优惠券
	receiveCoupon() {
		const { channel, coupon_list } = this.data;
		const list = coupon_list.map(item => item.coupon_no);

		app.request({
			url: requestApi.receiveCoupon,
			data: {
				is_new_ver: true,
				coupon_no: list.join(','),
				channel: channel
			},
		}, (data) => {
			wx.showToast({
				title: '登录成功，开启购物之旅，好礼将在1-2分钟内发放至您的优惠券账户',
				duration: 1000,
			})
		}, (error) => {
			wx.showToast({
                title: error,
                icon: 'error',
				duration: 1000,
			})
		})
    },
    // 获取类目列表
    getTypeData () {
        const { channel, params, cur } = this.data;

        wx.showLoading({
            title: '加载中...',
        });

        app.request({
            url: requestApi.categoryHall,
            data: {
                is_new_ver: true,
                channel: channel,
            },
            login: false,
        }, (data) => {
            if(data.original.ret_code == 200) {
                const d = data.original.data;

                params['keywords'] = d[cur].search_cate_name;
                params['gender_id'] = d[cur].gender_id;

                this.setData({
                    categoryList: d,
                    params
                }, () => {
                    this.getSearchGoods();
                    this.getFilterAll();
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            wx.hideLoading();
        })
    },
    // 选择分类
    chooseCategory(e) {
        const { index } = e.currentTarget.dataset;
        const { categoryList, params, isFixed, filterTop, top, height } = this.data;
        const info = categoryList[index];

        params['keywords'] = info.search_cate_name;
        params['gender_id'] = info.gender_id;
        
        this.setData({
            params: {
                gender_id: info.gender_id,
                goods_channel_source: 1,
                is_new_user_buy: 1,
                keywords: info.search_cate_name,
                search_goods_filter: 0
            },
            start: 0,
            cur: index
        }, () => {
            if (isFixed) {
                this.setData({
                    scrollTop: filterTop - top - height - 6,
                });
            }
            this.getSearchGoods();
            this.getFilterAll();
        })
    },
    pageScroll(e) {
        const { scrollTop } = e.detail;
        let { winWidth, winHeight, ratio, isFixed, filterTop, top, height } = this.data;
        let bg = '', opacity = 0, active = '';
        
        opacity = Math.ceil(((scrollTop / (winWidth * ratio)) >= 1 ? 1 : (scrollTop / (winWidth * ratio)) <= .5 ? 0 : (scrollTop / (winWidth * ratio))) * 100);

        if ((scrollTop / (winWidth * ratio)) <= 1) {
            opacity = (opacity / 100).toFixed(1);
        } else {
            opacity = 1;
        }

        if (opacity > .8) {
            active = 'active';
        }

        bg = 'rgba(255, 255, 255, '+ opacity +')';

        this.setData({
            navBgColor: bg,
            navClass: active,
            navOpacity: opacity
        })

        if (e.detail.scrollTop >= filterTop - top - height - 12) {
            if (!isFixed) {
                this.setData({
                    isFixed: true,
                    filterPaddingTop: top + height + 6
                })
            }
        } else {
            if (isFixed) {
                this.setData({
                    isFixed: false,
                    filterPaddingTop: 0
                })
            }
        }
    },
    getFilterList(e){
        const params = e.detail;
        const { filterTop,top, height } = this.data;
        this.setData({
            isShowFilter: false,
            start: 0,
            scrollTop: filterTop - top - height - 6,
            params
        })
        
        this.getSearchGoods();
    },
    onEnter() {

    },
    getSearchGoods() {
        let { params, oid, start, count, goodsList, cur } = this.data;
        const info  = extend(true, {}, params, { oid, start: start * count, count, is_new_ver: true });

        app.request({
            url: requestApi.searchGoods,
            data: info
        }, (d) => {
            if (d.original.ret_code == 200) {
                const info = d.original.data;
                // 商品列表
                let lists = [], filtrate = [], filterList = [], brandStory = null, recom = null, kingInfo = null, oidNum = oid;
                info.item_list.forEach(item => {
                    if (item.type == 31) {
                        brandStory = item.data;
                        brandStory.big_image.full_path = formatImage.cdnImage(brandStory.big_image.path, formatImage.THUMBNAIL_M);
                    } else if (item.type == 33) {
                        filterList = item.data.order || item.data.orders;
                        oidNum = item.data.selected_oid_default || '3';
                    } else if (item.type == 34) {
                        item.data.product_cover_image.full_path = formatImage.cdnImage(item.data.product_cover_image.path, formatImage.THUMBNAIL_M);
                        if (!goodsList.find(i => i.gid == item.data.gid) || !start) {
                            lists.push(item.data);
                        }
                    } else if (item.type == 41) {
                        recom = item.data;
                    } else if (item.type == 152) {
                        item.data.cover_image.full_path = formatImage.cdnImage(item.data.cover_image.path, formatImage.THUMBNAIL_M);
                        kingInfo = item.data;
                    }
                });

                if (start) {
                    lists = [].concat(goodsList, lists)
                }
                
                this.setData({
                    goodsList: lists,
                    start: start + 1,
                    oid: oidNum,
                    isMoreEnd: (lists.length >= info.total)
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
        })
    },
    loadMore() {
        const { isMoreEnd } = this.data;

        if (!isMoreEnd) {
            this.getSearchGoods();
        }
    },
    getFilterAll() {
        const { params } = this.data;

        app.request({
            url: requestApi.searchGoodsFilterAll,
            data: {
                params_info: JSON.stringify(params),
                type: 1,
                is_new_ver: true
            }
        }, (d) => {
            if (d.original.ret_code == 200) {
                this.setData({
                    filterInfo: d.original.data
                });
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
        })
    },
    openFilter() {
        if (this.data.filterInfo.total) {
            this.setData({
                isShowFilter: true
            })
        }
    },
    onShareAppMessage() {

    }
})